import json
from loguru import logger
from google.protobuf import empty_pb2

from goods_srv.proto import goods_pb2, goods_pb2_grpc
from goods_srv.model.models import Category


class CategoryServicer(goods_pb2_grpc.GoodsServicer):

    def category_model_to_dect(self, category):
        re = {}
        re["id"] = category.id
        re["name"] = category.name
        re["level"] = category.level
        re["parent"] = category.parent_category_id
        re["is_tab"] = category.is_tab
        return re

    @logger.catch
    def GetAllCategorysList(self, request: empty_pb2.Empty, context):
        """
            [{
                "name":"xxx",
                "id":xxx,
                "sub_category":[
                    {
                        "id":xxx,
                        "name":"xxx",
                        "sub_category":[
                        ]
                    }
                ]
            },{},{},{}]
        """
        level1 = []
        level2 = []
        level3 = []

        category_list_rsp = goods_pb2.CategoryListResponse()
        category_list_rsp.total = Category.select().count()
        for category in Category.select():
            category_rsp = goods_pb2.CategoryInfoResponse

            category_rsp.id = category.id
            category_rsp.name = category.name
            category_rsp.parentCategory = category.parent_category_id
            category_rsp.level = category.level
            category_rsp.isTab = category.is_tab
            category_list_rsp.data.append(category_rsp)
            if category.level == 1:
                level1.append(self.category_model_to_dect(category))
            elif category.level == 2:
                level2.append(self.category_model_to_dect(category))
            elif category.level == 3:
                level3.append(self.category_model_to_dect(category))
        # 开始整理
        for data3 in level3:
            for data2 in level2:
                if data3["parent"] == data2["id"]:
                    data2["sub_category"] = data2.get("sub_category", [data3]).append(data3)
                    # if "sub_category" not in data2:
                    #     data2["sub_category"] = [data3]
                    # else:
                    #     data2["sub_category"].append(data3)
        for data2 in level2:
            for data1 in level1:
                if data2["parent"] == data2["id"]:
                    data1["sub_category"] = data1.get("sub_category", [data2]).append(data2)
                    # if "sub_category" not in data1:
                    #     data1["sub_category"] = [data2]
                    # else:
                    #     data1["sub_category"].append(data2)
        category_list_rsp.jsonData = json.dumps(level1)
        return category_list_rsp
